<script lang="ts" setup name="VisceraAbility">
import {onMounted, reactive, computed, ref} from 'vue'
import useUser from '@/store/user'
import ToothCoordinates from './toothCoordinates.vue'
import {ElMessage, FormRules} from 'element-plus/es'
import {rejectVisceraFunction, saveVisceraFunction, getVisceraFunction, VisceraFunction, VisceraFunctionParams} from '@/api/medicalExaminerDesk/beginPhysicalExamination/visceraAbility'
import {ChecksOrRadios, fieldRequired} from '@/api/medicalExaminerDesk/beginPhysicalExamination'
import {showMessageBox} from '@/util/element'
const user = useUser.setup().store

const props = defineProps({
  // 体检登记表id
  checkupRegisterId: {
    type: String,
    required: true,
    default: ''
  },
  // 禁止编辑
  disEdit: {
    type: Boolean,
    required: true,
    default: false
  },
  // 性别
  gender: {
    type: String,
    required: false,
    default: ''
  }
})

// 保存和拒检的加载
const showSaveLoading = ref<boolean>(false)

// 默认牙齿
const defultTooth = '00000000|00000000|00000000|00000000'

// 脏器功能
const visceraAbilityForm = reactive<VisceraFunction>({
  oralCavity: '1', // 口唇
  dentalArch: '1', // 齿列
  dentalArchCheckboxs: ['1'], // 齿列复选
  hypodontia: defultTooth, // 缺齿
  caries: defultTooth, // 龋齿
  denlture: defultTooth, // 义齿（假牙）
  pharynxState: '1', // 咽部,
  eyesLeft: undefined, // 视力（左)
  eyeRight: undefined, // 视力（右)
  recEyeLeft: undefined, // 矫正视力(左)
  recEyeRight: undefined, // 矫正视力(右)
  hearingState: '1', // 听力
  motorFuncState: '1' // 运动功能
})
// 口唇
const oralCavityRadios: Array<ChecksOrRadios> = [
  {label: '红润', value: '1'},
  {label: '苍白', value: '2'},
  {label: '发绀', value: '3'},
  {label: '皲裂', value: '4'},
  {label: '疱疹', value: '5'}
]

// 咽部
const pharynxStateRadios: Array<ChecksOrRadios> = [
  {label: '无充血', value: '1'},
  {label: '充血', value: '2'},
  {label: '淋巴滤泡增生', value: '3'}
]

// 表单实例
const formRef = ref()

// 体检大类的体检医生姓名
const dutyDoctorName3 = computed(() => {
  return visceraAbilityForm.dutyDoctorName || (user.userInfor?.jobName === '医生' ? user.userInfor?.userName : '')
})

// 体检状态
const checkupStatus3 = computed(() => {
  return visceraAbilityForm.checkupStatus
})

// 校验
const rules = computed<FormRules>(() => {
  return {
    // 口唇
    oralCavity: [{required: fieldRequired('oralCavity'), message: '请选择口唇!', trigger: ['change', 'blur']}],
    // 齿列
    dentalArchCheckboxs: [{required: fieldRequired('dentalArch'), message: '请选择齿列!', trigger: ['change', 'blur']}],
    // 咽部
    pharynxState: [{required: fieldRequired('pharynxState'), message: '请选择咽部!', trigger: ['change', 'blur']}],
    // 视力（左)
    eyesLeft: [{required: fieldRequired('eyesLeft'), message: '请输入视力（左)!', trigger: ['change', 'blur']}],
    // 视力（右)
    eyeRight: [{required: fieldRequired('eyeRight'), message: '请输入视力（左)!', trigger: ['change', 'blur']}],
    // 矫正视力(左)
    recEyeLeft: [{required: fieldRequired('recEyeLeft'), message: '请输入矫正视力(左)!', trigger: ['change', 'blur']}],
    // 矫正视力(右)
    recEyeRight: [{required: fieldRequired('recEyeRight'), message: '请输入矫正视力(右)!', trigger: ['change', 'blur']}],
    // 听力
    hearingState: [{required: fieldRequired('hearingState'), message: '请选择口唇!', trigger: ['change', 'blur']}],
    // 运动功能
    motorFuncState: [{required: fieldRequired('motorFuncState'), message: '请选择齿列!', trigger: ['change', 'blur']}]
  }
})

/**
 * @description: 获取体检信息
 * @return {*}
 */
const getInitData = () => {
  props.checkupRegisterId &&
    getVisceraFunction(props.checkupRegisterId)
      .then((res) => {
        const {data} = res.data
        // 浅拷贝
        Object.assign(visceraAbilityForm, data)
        // 处理默认值
        visceraAbilityForm.dentalArchCheckboxs = data?.dentalArch?.split('|') || ['1'] // 齿列复选
        visceraAbilityForm.oralCavity = data?.oralCavity || '1' // 口唇
        visceraAbilityForm.pharynxState = data?.pharynxState || '1' // 咽部
        visceraAbilityForm.hearingState = data?.hearingState || '1' // 听力
        visceraAbilityForm.motorFuncState = data?.motorFuncState || '1' // 运动功能
      })
      .finally(() => {
        showSaveLoading.value = false
      })
}

// 表单参数
const formDataParams = computed<VisceraFunctionParams>(() => {
  return {
    oralCavity: visceraAbilityForm.oralCavity, // 口唇
    dentalArch: visceraAbilityForm.dentalArchCheckboxs?.join('|'), // 齿列
    hypodontia: visceraAbilityForm.dentalArchCheckboxs?.indexOf('2') !== -1 ? visceraAbilityForm.hypodontia : defultTooth, // 缺齿
    caries: visceraAbilityForm.dentalArchCheckboxs?.indexOf('3') !== -1 ? visceraAbilityForm.caries : defultTooth, // 龋齿
    denlture: visceraAbilityForm.dentalArchCheckboxs?.indexOf('4') !== -1 ? visceraAbilityForm.denlture : defultTooth, // 义齿（假牙）
    pharynxState: visceraAbilityForm.pharynxState, // 咽部,
    eyesLeft: visceraAbilityForm.eyesLeft, // 视力（左)
    eyeRight: visceraAbilityForm.eyeRight, // 视力（右)
    recEyeLeft: visceraAbilityForm.recEyeLeft, // 矫正视力(左)
    recEyeRight: visceraAbilityForm.recEyeRight, // 矫正视力(右)
    hearingState: visceraAbilityForm.hearingState, // 听力
    motorFuncState: visceraAbilityForm.motorFuncState // 运动功能
  }
})

/**
 * @description: 保存
 * @return {*}
 */
const onSave3 = () => {
  formRef.value &&
    formRef.value.validate((valid: boolean, fields) => {
      if (valid) {
        showSaveLoading.value = true
        const params = {
          ...formDataParams.value,
          checkupStatus: 2, // 已检
          id: visceraAbilityForm.id, // 表单Id
          checkupRegisterId: props.checkupRegisterId, // 体检登记表id
          dutyDoctorId: visceraAbilityForm.dutyDoctorId || user.userInfor?.id, // 体检医生id
          dutyDoctorName: visceraAbilityForm.dutyDoctorId !== user.userInfor?.id ? visceraAbilityForm.dutyDoctorName || user.userInfor?.userName : user.userInfor?.userName // 体检医生姓名
        }
        saveVisceraFunction(params)
          .then(() => {
            getInitData()
            ElMessage.success('保存成功!')
          })
          .catch((err) => {
            showSaveLoading.value = false
            console.warn(err)
          })
      } else {
        console.log(fields)
      }
    })
}

/**
 * @description: 拒检
 * @return {*}
 */
const onRejectInspection3 = () => {
  showMessageBox('是否对该体检大类进行拒检操作？', {title: '拒检确认', mesageType: 'base'})
    .then(() => {
      showSaveLoading.value = true
      const nullParams: VisceraFunctionParams = {...formDataParams.value}
      // 置空
      Object.keys(formDataParams.value)?.forEach((item) => {
        nullParams[item] = null
      })
      const params = {
        ...nullParams,
        checkupStatus: 1, // 1拒检
        id: visceraAbilityForm.id, // 表单Id
        checkupRegisterId: props.checkupRegisterId, // 体检登记表id
        dutyDoctorId: visceraAbilityForm.dutyDoctorId || user.userInfor?.id, // 体检医生id
        dutyDoctorName: visceraAbilityForm.dutyDoctorId !== user.userInfor?.id ? visceraAbilityForm.dutyDoctorName || user.userInfor?.userName : user.userInfor?.userName // 体检医生姓名
      }
      rejectVisceraFunction(params)
        .then(() => {
          ElMessage.success('拒检成功!')
          getInitData()
        })
        .catch((error) => {
          showSaveLoading.value = false
          console.warn(error)
        })
    })
    .catch((error) => {
      console.warn(error)
    })
}

/**
 * @description: 齿列勾选判断
 * @param {*} normal 是否正常
 * @return {*}
 */
const onChangeDentalArch = (normal: boolean) => {
  if (normal) {
    visceraAbilityForm.dentalArchCheckboxs.length ? (visceraAbilityForm.dentalArchCheckboxs = ['1']) : (visceraAbilityForm.dentalArchCheckboxs = [])
  } else {
    visceraAbilityForm.dentalArchCheckboxs = visceraAbilityForm.dentalArchCheckboxs.filter((item) => {
      return item !== '1'
    })
  }
}

onMounted(() => {
  getInitData()
})
</script>
<template>
  <el-form ref="formRef" class="d-check-up-desk-content" label-position="top" :model="visceraAbilityForm" :rules="rules" :disabled="disEdit">
    <el-form-item label="口腔" prop="" class="viscera-ability-form-item">
      <el-form-item label="口唇:" prop="oralCavity" class="oral-cavity-form-item">
        <el-radio-group v-model="visceraAbilityForm.oralCavity">
          <el-radio v-for="item in oralCavityRadios" :key="item.value" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="齿列:" prop="dentalArchCheckboxs" class="oral-cavity-form-item">
        <el-checkbox-group v-model="visceraAbilityForm.dentalArchCheckboxs" class="dental-arch-checkboxs">
          <el-checkbox label="1" @change="onChangeDentalArch(true)">
            正常
          </el-checkbox>
          <el-checkbox label="2" @change="onChangeDentalArch(false)">
            缺齿
          </el-checkbox>
          <ToothCoordinates
            :tooth-data-str="visceraAbilityForm.hypodontia || ''"
            :disabled="visceraAbilityForm.dentalArchCheckboxs.indexOf('2') === -1"
            @set-tooth-data="
              (data) => {
                visceraAbilityForm.hypodontia = data.join('|')
              }
            "
          />
          <el-checkbox label="3" @change="onChangeDentalArch(false)">
            龋齿
          </el-checkbox>
          <ToothCoordinates
            :tooth-data-str="visceraAbilityForm.caries || ''"
            :disabled="visceraAbilityForm.dentalArchCheckboxs.indexOf('3') === -1"
            @set-tooth-data="
              (data) => {
                visceraAbilityForm.caries = data.join('|')
              }
            "
          />
          <el-checkbox label="4" @change="onChangeDentalArch(false)">
            义齿（假牙）
          </el-checkbox>
          <ToothCoordinates
            :tooth-data-str="visceraAbilityForm.denlture || ''"
            :disabled="visceraAbilityForm.dentalArchCheckboxs.indexOf('4') === -1"
            @set-tooth-data="
              (data) => {
                visceraAbilityForm.denlture = data.join('|')
              }
            "
          />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="咽部:" prop="pharynxState" class="oral-cavity-form-item">
        <el-radio-group v-model="visceraAbilityForm.pharynxState">
          <el-radio v-for="item in pharynxStateRadios" :key="item.value" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form-item>
    <el-form-item label="视力" prop="" class="viscera-ability-form-item">
      <div class="inline-input-number-item inline-form">
        <el-form-item label="视力(左):" prop="eyesLeft">
          <el-input-number v-model="visceraAbilityForm.eyesLeft" :controls="false" :precision="1" :min="0" :max="5.4" />
        </el-form-item>
        <el-form-item label="视力(右):" prop="eyeRight">
          <el-input-number v-model="visceraAbilityForm.eyeRight" :controls="false" :precision="1" :min="0" :max="5.4" />
        </el-form-item>
        <el-form-item label="矫正视力(左):" prop="recEyeLeft">
          <el-input-number v-model="visceraAbilityForm.recEyeLeft" :controls="false" :precision="1" :min="0" :max="5.4" />
        </el-form-item>
        <el-form-item label="矫正视力(右):" prop="recEyeRight">
          <el-input-number v-model="visceraAbilityForm.recEyeRight" :controls="false" :precision="1" :min="0" :max="5.4" />
        </el-form-item>
      </div>
    </el-form-item>
    <el-form-item label="听力" prop="hearingState" class="viscera-ability-form-item">
      <el-radio-group v-model="visceraAbilityForm.hearingState">
        <el-radio label="1">
          听见
        </el-radio>
        <el-radio label="2">
          听不清或无法听见
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="运动功能" prop="motorFuncState" class="viscera-ability-form-item">
      <el-radio-group v-model="visceraAbilityForm.motorFuncState">
        <el-radio label="1">
          可顺利完成
        </el-radio>
        <el-radio label="2">
          无法独立完成任何一个动作
        </el-radio>
      </el-radio-group>
    </el-form-item>
  </el-form>
  <div class="d-check-up-desk-footer d-common-flex-center d-common-width-full">
    <span class="doctor">体检医生：</span>
    <el-input v-model="dutyDoctorName3" disabled />
    <el-button type="primary" :loading="showSaveLoading" :disabled="disEdit" @click="onSave3()">
      保存
    </el-button>
    <el-button type="danger" :loading="showSaveLoading" :disabled="(checkupStatus3 && checkupStatus3 === 1) || disEdit" plain @click="onRejectInspection3()">
      拒检
    </el-button>
  </div>
</template>
<style scoped lang="less">
.viscera-ability-form-item {
  padding-bottom: 24px;
  margin-bottom: 19px;
  border-bottom: 1px solid rgba(195, 201, 210, 1);
  &:last-child {
    border-bottom: none;
  }
  :deep(.el-form-item__label) {
    color: var(--d-font-color-text);
    font-weight: bold;
    display: inline-flex;
    align-items: center;
  }
  :deep(.el-form-item__content) {
    margin-left: 23px;
  }
}
.inline-input-number-item {
  :deep(.el-form-item__label) {
    font-weight: normal;
    margin: 0 !important;
  }
  :deep(.el-form-item__content) {
    margin: 0;
  }
  .el-input-number,
  .el-input {
    width: 100px;
    height: 32px;
    margin: 0 5px;
  }
}
.oral-cavity-form-item {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  :deep(.el-form-item__label) {
    font-weight: normal;
    margin: 0 !important;
  }
}
.dental-arch-checkboxs {
  display: flex;
  align-items: center;
  .el-checkbox {
    margin: 0;
    &:not(:first-child) {
      margin-left: 32px;
    }
  }
  margin: 0;
  :deep(.el-checkbox__label) {
    display: flex;
    align-items: center;
  }
}
.inline-form {
  .el-form-item {
    display: inline-flex;
    vertical-align: middle;
    margin-right: 30px;
  }
}
</style>
